package top.xinsix.est.tools.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.logging.Logger;


/**
 * OSS的操作工具类
 */
@Component
public class OssUtils {
    private final static Logger logger=Logger.getLogger("OssUtils");
    @Autowired
    private OssConfig ossConfig;
    //创建OSS连接对象
    public OSS getOSSClient(){
        String endpoint = ossConfig.getEndPoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        // 创建OSSClient实例。
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
    /**
     * 文件上传
     * 根据文件全路径名称使用输入流的方式上传文件到oss
     * @param file
     * @param fileName est/brand/huawei/huawei.png
     * @return
     */
    public String uploadByStream(File file, String fileName) {
        String resultStr = null;
        try {
            InputStream is = new FileInputStream(file);
            resultStr = uploadByStream(is, fileName);
        }catch (Exception e){
            logger.info("上传阿里云OSS服务器异常:"+ e.getMessage());
        }
        return resultStr;
    }
    /**
     * 文件上传
     * @param is
     * @param fileName est/brand/huawei/huawei.png
     * @return
     */
    public String uploadByStream(InputStream is, String fileName) {
        String resultStr = null;
        OSS ossClient = null;
        try {
            ossClient = getOSSClient();
            PutObjectResult putObjectResult = ossClient.putObject(
                    ossConfig.getBucketName(), fileName, is);
            resultStr = putObjectResult.getETag();
        }catch (Exception e){
            logger.info("输入流方式上传阿里云OSS服务器异常:"+ e.getMessage());
        }finally {
            ossClient.shutdown();
        }
        return resultStr;
    }
    /**
     * 下载
     * @param fileId
     * @param fileName 文件名称
     * @return
     */
    public final void download(String fileId, String fileName,
                               HttpServletResponse response) {
        try {
            OSS client = getOSSClient();
            int i = fileName.lastIndexOf("\\");
            fileName = fileName.substring(i + 1);

            //获取fileId对应的阿里云上的文件对象
            OSSObject ossObject = client.getObject(ossConfig.getBucketName(), fileId);
            BufferedInputStream in =
                    new BufferedInputStream(ossObject.getObjectContent());
            BufferedOutputStream out =
                    new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode(fileName, "utf-8"));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);
            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
            // 关闭客户端连接
            client.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  根据key删除OSS服务器上的文件
     * @param diskName fieldid
     * @param fileName 文件名称
     */
    public void deleteFile(String diskName, String fileName) {
        deleteFile(diskName + fileName);
    }

    /**
     *  根据key删除OSS服务器上的文件
     * @param fileName 文件名称
     */
    public void deleteFile(String fileName) {
        OSS client = getOSSClient();
        client.deleteObject(ossConfig.getBucketName(), fileName);
    }

}
